package main

import (
	"fmt"
	"github.com/ClickHouse/clickhouse-go"
	"github.com/jmoiron/sqlx"
	"log"
	"time"
)

func main() {
	connect, err := sqlx.Open("clickhouse", "tcp://192.168.3.34:9000?debug=true")
	if err != nil {
		log.Fatal(err)
	}
	if err := connect.Ping(); err != nil {
		if exception, ok := err.(*clickhouse.Exception); ok {
			fmt.Printf("[%d] %s \n%s\n", exception.Code, exception.Message, exception.StackTrace)
		} else {
			fmt.Println(err)
		}
		return
	}

	_, err = connect.Exec(`
		-- auto-generated definition
			 CREATE TABLE queue (
				uuid String,
				type String
			  ) ENGINE = Kafka SETTINGS
						  kafka_broker_list = '192.168.3.14:19092,192.168.3.50:19092,192.168.3.59:19092',
						  kafka_topic_list = 'TagPosition',
						  kafka_group_name = 'rtfm_new_group',
						  kafka_format = 'JSONEachRow',
						  kafka_row_delimiter = '\n',
						  kafka_num_consumers = 2;
	`)
	if err != nil {
		log.Fatal(err)
	}

	_, err = connect.Exec(`
		-- auto-generated definition
			 CREATE TABLE daily (
				uuid String,
				type String
			) ENGINE =MergeTree 
					SETTINGS index_granularity = 8192;
	`)
	if err != nil {
		log.Fatal(err)
	}

	_, err = connect.Exec(`
		-- auto-generated definition
			 CREATE MATERIALIZED VIEW consumer TO daily
			AS SELECT uuid,type	FROM queue ;
	`)
	if err != nil {
		log.Fatal(err)
	}

	var a int
	if err := connect.Select(&a, "SELECT COUNT(*) FROM daily"); err != nil {
		log.Fatal(err)
	}
	for {
		time.Sleep(3 * time.Second)
		log.Println(a)
	}
	//if _, err := connect.Exec("DROP TABLE example"); err != nil {
	//	log.Fatal(err)
	//}
}
